const jwt = require('jsonwebtoken');
const helper = require('../../util/helper');
const config = require('../../config/environment/index');

exports.login = async(ctx) => {
  let userName = ctx.request.body.user_name || '',
      password = ctx.request.body.password || '';
  if (!userName || !password) {
    ctx.body = {
      result: 201,
      message: '用户名或密码不能为空'
    };
    return;
  }

  try {
    let results = await ctx.execSql.query(`SELECT manager_id, hash_password, salt FROM manager WHERE role_id=0 and manager_name = ?`, userName);
    if (results.length > 0) {
      let hashedPassword = results[0].hash_password,
          salt = results[0].salt,
          hashPassword = helper.encryptPassword(password, salt);
          console.log(password,salt,hashPassword);
      if (hashedPassword === hashPassword) {
        ctx.session.user = userName;
        // 用户token
        const userToken = {
          name: userName,
          id: results[0].manager_id
        };
        // 签发token
        const token = jwt.sign(userToken, config.tokenSecret, { expiresIn: '2h' });
        ctx.body = {
          result: 200,
          token: token,
          message: ''
        };
      } else {
        ctx.body = {
          result: 201,
          message: '用户名或密码错误'
        };
      }
    } else {
      ctx.body = {
        result: 201,
        message: '用户名或密码错误'
      };
    }
  } catch (error) {
    console.log(error);
    ctx.body = {
      result: 202,
      message: '查询数据出错'
    };
  }
}

exports.signOut = async(ctx) => {
  ctx.session.user = null;
  ctx.body = {
    result: 200,
    message: ''
  };
}




